<template>
  <div class="chat-container">
    <!-- 好友列表 -->
    <div class="friend-list">
      <h3>好友列表</h3>
      <ul>
        <li 
          v-for="friend in friendList"
          :key="friend.id"
          @click="selectFriend(friend)"
          :class="{ active: selectedFriend?.id === friend.id }"
        >
          <div class="avatar-container">
            <img :src="friend.userPic || avatar" alt="Avatar" class="friend-avatar" />
            <span v-if="friend.unreadCount" class="notification-dot"></span>
          </div>
          <span>{{ friend.username }}</span>
          <span v-if="friend.unreadCount" class="unread-count">{{ friend.unreadCount }}</span>
        </li>
      </ul>
    </div>

    <!-- 聊天界面 -->
    <div class="chat-box" v-if="selectedFriend">
      <div class="chat-header">
        <h3>{{ selectedFriend.username }}</h3>
        <div class="header-actions">
          <button class="video-call-btn" @click="startVideoCall" :disabled="!isOnline">
            <img :src="videoCallIcon" alt="视频通话" class="video-icon" /> 视频通话
          </button>
          <span class="online-status" :class="{ 'online': isOnline }">
            {{ isOnline ? '在线' : '离线' }}
          </span>
        </div>
      </div>
      
      <div class="message-container" ref="messageContainer">
        <!-- 加载更多按钮 -->
        <div v-if="hasMoreMessages" class="load-more" :class="{ 'loading': isLoading }">
          <span v-if="isLoading">加载中...</span>
          <button v-else @click="loadMoreHistory">加载更多</button>
        </div>

        <!-- 消息列表 -->
        <div class="messages-wrapper">
          <div v-for="(message, index) in messages" :key="index">
            <!-- 日期分隔线 -->
            <div class="date-divider" v-if="shouldShowDateDivider(message, messages[index-1])">
              {{ formatDateDivider(message.sendTime) }}
            </div>
            
            <div 
              :class="[
                'message-item',
                message.sendUserId === userInfo.id.toString() ? 'my-message' : 'friend-message'
              ]"
            >
              <div class="message-content-wrapper">
                <div class="message-content">
                  <p>{{ message.sendText }}</p>
                </div>
                <span class="message-time">{{ formatTime(message.sendTime) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 输入框 -->
      <div class="input-container">
        <input 
          v-model="newMessage" 
          placeholder="输入消息..." 
          @keyup.enter="sendMessage"
          :disabled="!isOnline"
        />
        <button @click="sendMessage" :disabled="!isOnline || !newMessage.trim()">发送</button>
      </div>
    </div>

    <!-- 未选择好友时的提示 -->
    <div v-else class="no-chat-selected">
      <p>请选择一个好友开始聊天</p>
    </div>
    
    <!-- 视频通话组件 -->
    <VideoCall
      v-if="showVideoCall"
      :isVisible="showVideoCall"
      :friendId="videoCallInfo.friendId"
      :friendName="videoCallInfo.friendName"
      :userId="userInfo.id.toString()"
      :isIncoming="videoCallInfo.isIncoming"
      :offerData="videoCallInfo.offerData"
      @close="closeVideoCall"
      @callStarted="handleCallStarted"
      @callEnded="handleCallEnded"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from "vue";
import { getFriendList } from "@/api/friend";
import { 
  sendChatMessage, 
  addChatListener, 
  removeChatListener, 
  connectWebSocket,
  addConnectionStatusListener,
  removeConnectionStatusListener,
  disconnectWebSocket,
  clearAllListeners
} from "@/utils/websocket";
import useUserInfoStore from "@/stores/userInfo";
import { useTokenStore } from "@/stores/token";
import axios from "axios";
import avatar from '@/assets/default.png';
import videoCallIcon from '@/assets/视频通话.png';
import VideoCall from "@/components/VideoCall.vue";
import * as webrtc from "@/utils/webrtc";

// 创建axios实例
const axiosInstance = axios.create();

// 获取token store
const tokenStore = useTokenStore();

// 添加请求拦截器
axiosInstance.interceptors.request.use(
  config => {
    // 从pinia获取token
    const token = tokenStore.token;
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axiosInstance.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response?.status === 401) {
      // token过期或无效，跳转到登录页
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

const userInfoStore = useUserInfoStore();
const userInfo = userInfoStore.info;

const friendList = ref([]);
const selectedFriend = ref(null);
const messages = ref([]);
const newMessage = ref("");
const isOnline = ref(true);
const messageContainer = ref(null);
const isLoading = ref(false);
const hasMoreMessages = ref(true);
const currentPage = ref(1);
const pageSize = 20;

// 视频通话相关
const showVideoCall = ref(false);
const videoCallInfo = ref({
  friendId: '',
  friendName: '',
  isIncoming: false,
  offerData: ''
});

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  try {
    const date = new Date(time);
    if (isNaN(date.getTime())) {
      console.error('无效的时间格式:', time);
      return '';
    }
    
    const now = new Date();
    const isToday = date.toDateString() === now.toDateString();
    const isYesterday = new Date(now - 86400000).toDateString() === date.toDateString();
    
    if (isToday) {
      return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    } else if (isYesterday) {
      return `昨天 ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`;
    } else {
      return date.toLocaleDateString('zh-CN', { 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit', 
        minute: '2-digit'
      });
    }
  } catch (error) {
    console.error('时间格式化错误:', error);
    return '';
  }
};

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
  }
};

// 加载好友列表
const loadFriends = async () => {
  try {
    const { data } = await getFriendList(userInfo.id);
    friendList.value = data.map(friend => ({
      ...friend,
      unreadCount: 0
    }));
  } catch (error) {
    console.error("加载好友列表失败：", error);
  }
};

// 选择好友进行聊天
const selectFriend = async (friend) => {
  try {
    console.log("选择好友:", friend);
    selectedFriend.value = friend;
    messages.value = []; // 清空消息
    hasMoreMessages.value = true; // 重置加载更多状态
    currentPage.value = 1; // 重置页码
    
    await fetchChatHistory(friend.id);
    
    // 清除未读消息计数
    if (friend.unreadCount) {
      console.log(`清除好友 ${friend.username} 的未读消息数`);
      friend.unreadCount = 0;
    }
  } catch (error) {
    console.error("选择好友时出错:", error);
  }
};

// 加载聊天历史记录
const fetchChatHistory = async (friendId, page = 1) => {
  if (isLoading.value || (!hasMoreMessages.value && page > 1)) return;
  
  try {
    isLoading.value = true;
    const response = await axiosInstance.get(`/api/chat/history`, {
      params: {
        userId: userInfo.id.toString(),
        friendId: friendId.toString(),
        page: page,
        pageSize: pageSize
      }
    });
    
    console.log("获取到的历史记录:", response.data);
    
    const history = Array.isArray(response.data) ? response.data : [];
    
    if (history.length < pageSize) {
      hasMoreMessages.value = false;
    }
    
    // 确保消息按时间排序，最早的消息在上面
    const sortedHistory = history.sort((a, b) => 
      new Date(a.sendTime).getTime() - new Date(b.sendTime).getTime()
    );
    
    if (page === 1) {
      messages.value = sortedHistory;
    } else {
      // 合并并重新排序所有消息
      messages.value = [...sortedHistory, ...messages.value].sort((a, b) => 
        new Date(a.sendTime).getTime() - new Date(b.sendTime).getTime()
      );
    }
    
    currentPage.value = page;
    if (page === 1) {
      await scrollToBottom();
    }
  } catch (error) {
    console.error("加载聊天记录失败：", error);
    console.error("错误详情：", error.response?.data || error.message);
    messages.value = [];
  } finally {
    isLoading.value = false;
  }
};

// 处理收到的消息
const handleIncomingMessage = (message) => {
  console.log("处理收到的消息:", message);
  
  // 处理视频通话相关消息
  if (message.msgType === 'video-offer' || 
      message.msgType === 'video-answer' || 
      message.msgType === 'ice-candidate' || 
      message.msgType === 'video-hangup' ||
      message.msgType === 'screen-share-started' ||
      message.msgType === 'screen-share-ended') {
    
    // 如果是视频通话请求且当前没有显示视频通话界面，则显示来电界面
    if (message.msgType === 'video-offer' && !showVideoCall.value) {
      handleVideoOffer(message);
    } 
    // 其他视频通话相关消息直接转发给WebRTC处理
    else if (message.msgType === 'video-answer') {
      webrtc.handleVideoAnswer(message.sendText);
    }
    else if (message.msgType === 'ice-candidate') {
      webrtc.handleIceCandidate(message.sendText);
    }
    else if (message.msgType === 'video-hangup') {
      webrtc.handleHangup();
      // 如果当前正在显示视频通话界面，则关闭它
      if (showVideoCall.value) {
        closeVideoCall();
      }
    }
    // 处理屏幕分享状态消息
    else if (message.msgType === 'screen-share-started') {
      console.log('对方开始分享屏幕');
      // 通知WebRTC模块更新屏幕分享状态
      webrtc.handleScreenShareStatus(true);
      // 不记录屏幕共享开始消息到聊天历史
      return;
    }
    else if (message.msgType === 'screen-share-ended') {
      console.log('对方停止分享屏幕');
      // 通知WebRTC模块更新屏幕分享状态
      webrtc.handleScreenShareStatus(false);
      // 不记录屏幕共享结束消息到聊天历史
      return;
    }
    return;
  }
  
  // 确保messages.value是数组
  if (!Array.isArray(messages.value)) {
    messages.value = [];
  }
  
  // 检查消息是否属于当前聊天
  if (selectedFriend.value) {
    const isCurrentChat = 
      (message.sendUserId === selectedFriend.value.id.toString() && message.receiveUserId === userInfo.id.toString()) ||
      (message.sendUserId === userInfo.id.toString() && message.receiveUserId === selectedFriend.value.id.toString());
    
    if (isCurrentChat) {
      // 检查消息是否已存在
      const messageExists = messages.value.some(m => 
        m.sendUserId === message.sendUserId && 
        m.receiveUserId === message.receiveUserId && 
        m.sendText === message.sendText &&
        m.sendTime === message.sendTime
      );
      
      if (!messageExists) {
        console.log("添加新消息到消息列表:", message);
        // 将新消息添加到数组末尾
        messages.value = [...messages.value, message];
        scrollToBottom();
      }
    } else if (message.sendUserId !== userInfo.id.toString()) {
      // 更新未读消息计数（只有当消息不是自己发送的时才更新）
      const friend = friendList.value.find(f => f.id.toString() === message.sendUserId);
      if (friend) {
        friend.unreadCount = (friend.unreadCount || 0) + 1;
        console.log(`更新好友 ${friend.username} 的未读消息数为 ${friend.unreadCount}`);
      }
    }
  } else if (message.sendUserId !== userInfo.id.toString()) {
    // 如果当前没有选中的好友，更新未读消息计数（只有当消息不是自己发送的时才更新）
    const friend = friendList.value.find(f => f.id.toString() === message.sendUserId);
    if (friend) {
      friend.unreadCount = (friend.unreadCount || 0) + 1;
      console.log(`更新好友 ${friend.username} 的未读消息数为 ${friend.unreadCount}`);
    }
  }
};

// 处理视频通话请求
const handleVideoOffer = (message) => {
  console.log('收到视频通话请求:', message);
  const senderId = message.sendUserId;
  const friend = friendList.value.find(f => f.id.toString() === senderId);
  
  if (friend) {
    // 如果已经在通话中，则忽略新的通话请求
    const callStatus = webrtc.getCallStatus();
    if (callStatus.isCallInProgress) {
      console.log('已有通话正在进行中，忽略新的通话请求');
      return;
    }
    
    // 确保没有正在显示的视频通话界面
    if (showVideoCall.value) {
      closeVideoCall();
    }
    
    // 延迟一下，确保之前的资源已释放
    setTimeout(() => {
      videoCallInfo.value = {
        friendId: senderId,
        friendName: friend.username,
        isIncoming: true,
        offerData: message.sendText
      };
      
      showVideoCall.value = true;
    }, 500);
  } else {
    console.warn('收到未知好友的视频通话请求:', senderId);
  }
};

// 发送聊天消息
const sendMessage = async () => {
  if (!newMessage.value.trim() || !isOnline.value) return;

  const message = {
    sendUserId: userInfo.id.toString(),
    receiveUserId: selectedFriend.value.id.toString(),
    msgType: "text",
    sendText: newMessage.value,
    sendTime: new Date().toISOString()
  };

  try {
    // 先发送消息
    const success = await sendChatMessage(message);
    if (success) {
      // 发送成功后清空输入框
      newMessage.value = "";
      // 消息会通过 WebSocket 接收到并显示，这里不需要手动添加
    } else {
      console.error("发送消息失败");
    }
  } catch (error) {
    console.error("发送消息失败：", error);
  }
};

// 开始视频通话
const startVideoCall = () => {
  if (!selectedFriend.value || !isOnline.value) return;
  
  // 检查是否已经在通话中
  const callStatus = webrtc.getCallStatus();
  if (callStatus.isCallInProgress) {
    alert('已有通话正在进行中，请先结束当前通话');
    return;
  }
  
  // 确保没有正在显示的视频通话界面
  if (showVideoCall.value) {
    closeVideoCall();
  }
  
  // 延迟一下，确保之前的资源已释放
  setTimeout(() => {
    console.log('开始视频通话，好友ID:', selectedFriend.value.id);
    videoCallInfo.value = {
      friendId: selectedFriend.value.id.toString(),
      friendName: selectedFriend.value.username,
      isIncoming: false,
      offerData: ''
    };
    
    showVideoCall.value = true;
  }, 500);
};

// 关闭视频通话
const closeVideoCall = () => {
  console.log('关闭视频通话界面');
  
  // 确保结束WebRTC通话
  webrtc.endCall();
  
  // 延迟一下再隐藏界面，确保资源释放
  setTimeout(() => {
    showVideoCall.value = false;
  }, 100);
};

// 处理通话开始
const handleCallStarted = () => {
  console.log('视频通话已开始');
};

// 处理通话结束
const handleCallEnded = () => {
  console.log('视频通话已结束');
};

// 加载更多历史记录
const loadMoreHistory = async () => {
  if (selectedFriend.value) {
    await fetchChatHistory(selectedFriend.value.id, currentPage.value + 1);
  }
};

// 监听消息容器滚动
const handleScroll = async (e) => {
  const container = e.target;
  // 当滚动到顶部时加载更多历史消息
  if (container.scrollTop === 0 && hasMoreMessages.value && !isLoading.value) {
    const oldHeight = container.scrollHeight;
    await loadMoreHistory();
    // 保持滚动位置，避免加载历史消息时跳动
    await nextTick();
    container.scrollTop = container.scrollHeight - oldHeight;
  }
};

// 页面加载时，连接WebSocket并加载数据
onMounted(async () => {
  try {
    console.log("组件挂载 - 开始加载数据");
    await loadFriends();
    console.log("好友列表加载完成:", friendList.value);
    
    // 如果URL中有指定的好友ID，自动选择该好友
    const urlParams = new URLSearchParams(window.location.search);
    const friendId = urlParams.get('friendId');
    if (friendId) {
      const friend = friendList.value.find(f => f.id.toString() === friendId);
      if (friend) {
        console.log("自动选择好友:", friend);
        await selectFriend(friend);
      }
    }
    
    connectWebSocket(userInfo.id);
    addChatListener(handleIncomingMessage);
    
    // 初始化WebRTC
    webrtc.initWebRTC(userInfo.id.toString());
    
    // 添加滚动事件监听
    if (messageContainer.value) {
      messageContainer.value.addEventListener('scroll', handleScroll);
    }
  } catch (error) {
    console.error("组件挂载时出错:", error);
  }
});

// 组件卸载时，移除监听器
onUnmounted(() => {
  removeChatListener(handleIncomingMessage);
  
  // 移除滚动事件监听
  if (messageContainer.value) {
    messageContainer.value.removeEventListener('scroll', handleScroll);
  }
});

watch(selectedFriend, async (newFriend) => {
  if (newFriend) {
    await fetchChatHistory(newFriend.id);
  }
});

// 判断是否需要显示日期分隔线
const shouldShowDateDivider = (currentMessage, previousMessage) => {
  if (!previousMessage) return true;
  
  const currentDate = new Date(currentMessage.sendTime).toDateString();
  const previousDate = new Date(previousMessage.sendTime).toDateString();
  
  return currentDate !== previousDate;
};

// 格式化日期分隔线
const formatDateDivider = (time) => {
  const date = new Date(time);
  const now = new Date();
  const yesterday = new Date(now - 86400000);
  
  if (date.toDateString() === now.toDateString()) {
    return '今天';
  } else if (date.toDateString() === yesterday.toDateString()) {
    return '昨天';
  } else {
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  width: 100%;
  height: 500px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.friend-list {
  width: 250px;
  border-right: 1px solid #eee;
  padding: 15px;
  background: #f5f5f5;
}

.friend-list h3 {
  margin: 0 0 15px 0;
  color: #333;
}

.friend-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.friend-list li {
  padding: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  border-radius: 8px;
  margin-bottom: 5px;
  position: relative;
}

.friend-list li:hover {
  background: #e8e8e8;
}

.friend-list li.active {
  background: #e3f2fd;
}

.avatar-container {
  position: relative;
  margin-right: 12px;
  width: 40px;
  height: 40px;
  display: inline-block;
}

.notification-dot {
  position: absolute;
  top: -3px;
  right: -3px;
  width: 12px;
  height: 12px;
  background-color: #ff4081;
  border-radius: 50%;
  border: 2px solid #f5f5f5;
  z-index: 10;
}

.friend-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.unread-count {
  position: absolute;
  right: 12px;
  background: #ff4081;
  color: white;
  border-radius: 50%;
  padding: 2px 6px;
  font-size: 12px;
  min-width: 18px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.chat-box {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.video-call-btn {
  display: flex;
  align-items: center;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  font-size: 14px;
}

.video-call-btn:hover {
  background-color: #45a049;
}

.video-call-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.video-icon {
  width: 24px;
  height: 24px;
  margin-right: 5px;
  vertical-align: middle;
}

.online-status {
  font-size: 14px;
  color: #999;
}

.online-status.online {
  color: #4caf50;
}

.message-container {
  flex-grow: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f9f9f9;
  display: flex;
  flex-direction: column;
}

.messages-wrapper {
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.message-item {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
  justify-content: flex-start;
}

.my-message {
  justify-content: flex-end;
}

.message-content-wrapper {
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.my-message .message-content {
  background: #e3f2fd;
  border-radius: 15px 15px 0 15px;
  color: #000;
}

.friend-message .message-content {
  background: white;
  border-radius: 15px 15px 15px 0;
  color: #000;
}

.message-content {
  padding: 10px 15px;
  position: relative;
  word-break: break-word;
  margin-bottom: 5px;
}

.message-content p {
  margin: 0;
  padding: 0;
}

.message-time {
  font-size: 12px;
  color: #999;
  align-self: flex-end;
}

.my-message .message-time {
  text-align: right;
}

.friend-message .message-time {
  text-align: left;
}

.input-container {
  padding: 15px;
  background: white;
  border-top: 1px solid #eee;
  display: flex;
  gap: 10px;
}

.input-container input {
  flex-grow: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
}

.input-container input:focus {
  border-color: #409eff;
}

.input-container button {
  padding: 10px 20px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  transition: background 0.3s;
}

.input-container button:hover {
  background: #66b1ff;
}

.input-container button:disabled {
  background: #a0cfff;
  cursor: not-allowed;
}

.load-more {
  text-align: center;
  padding: 10px;
  background: #f5f5f5;
  margin-bottom: 10px;
  border-radius: 4px;
  width: 100%;
  align-self: center;
}

.load-more.loading {
  color: #999;
}

.load-more button {
  background: none;
  border: none;
  color: #409eff;
  cursor: pointer;
  padding: 5px 10px;
}

.load-more button:hover {
  text-decoration: underline;
}

.date-divider {
  text-align: center;
  margin: 20px 0;
  position: relative;
  color: #999;
  font-size: 12px;
  width: 100%;
  align-self: center;
}

.date-divider::before,
.date-divider::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 40%;
  height: 1px;
  background: #eee;
}

.date-divider::before {
  left: 0;
}

.date-divider::after {
  right: 0;
}

.no-chat-selected {
  flex-grow: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f9f9f9;
  color: #999;
}
</style>
